package com.godfeer.rest.common.aop;

import com.godfeer.rest.bean.ResponseBean;
import com.godfeer.rest.common.exception.ip.RequestLimitException;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author : godfeer@aliyun.com
 * @date : 2018/6/7/007
 **/
@RestControllerAdvice
public class ExceptionRestController {

    private Logger logger = Logger.getLogger(ExceptionRestController.class);

    /**
     * 捕捉shiro的异常
     * @param e ShiroException
     * @return ResponseBean
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResponseBean handle401(ShiroException e) {
        return new ResponseBean(401, e.getMessage(), null);
    }

    /**
     * 捕捉UnauthorizedException
     * @return ResponseBean
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ResponseBean handle401() {
        return new ResponseBean(401, "Unauthorized", null);
    }

    /**
     * 捕捉RequestLimitException
     * @return ResponseBean
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(RequestLimitException.class)
    public ResponseBean requestLimitException(HttpServletRequest request, RequestLimitException ex) {
        return new ResponseBean(500, ex.getMessage(), null);
    }

    /**
     * 捕捉其他所有异常
     * @param request HttpServletRequest
     * @param ex Throwable
     * @return ResponseBean
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean globalException(HttpServletRequest request, Throwable ex) {

        logger.info(ex.getMessage());
        return new ResponseBean(getStatus(request).value(), ex.getMessage(), null);
    }



    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }




}
